<template>
<div>
  <div class="row-header">
    <el-form :inline="true">
      <el-form-item label=" " label-width="50px">
        <el-input placeholder="请输入角色名字" size="small" style="width: 100%;" v-model="role"></el-input>
      </el-form-item>
    </el-form>
    <div class="row-form-btn">
      <el-button type="shenda" size="small" @click="addRoles" v-preventReClick>添加</el-button>
    </div>
  </div>
  <div class="split-line"></div>
  <div class="row-main">
    <el-table :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }" :data="tableData" tooltip-effect="dark" class="row-main-table" @selection-change="handleSelectionChange" v-loading.fullscreen="tableLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.2)">
      <el-table-column prop="name" label="角色名字" align="center"></el-table-column>
      <el-table-column prop="insertTime" label="插入时间" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-dropdown trigger="click">
            <div>
              <svg-icon class="el-dropdown-link" icon-class="operation"></svg-icon>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-button class="operation" v-if="scope.row.roleChar!='OEM_ADMIN'&amp;&amp;scope.row.roleChar!='DAILI_ADMIN'" @click="showDeleteRole(scope.row)" style="margin: 0 auto; width: 100%;">删除</el-button>
              <el-button class="operation" v-if="scope.row.roleChar!='OEM_ADMIN'&amp;&amp;scope.row.roleChar!='DAILI_ADMIN'" @click="showAllocationPermission(scope.row)">分配权限</el-button>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="pageSize" layout="total,sizes,prev, pager, next, jumper" :total="total" :page-sizes="[10,20,50,100]" background class="row-main-pager"></el-pagination>

  </div>
  <!-- 删除-->
  <el-dialog class="delete" top="33vh" :visible.sync="deleteRoles" :append-to-body="true" width="30%"><span style="display: flex; justify-content: center; color: red; font-family: 微软雅黑;">确定删除该角色吗？</span><span class="dialog-footer" slot="footer">
      <el-button @click="deleteRoles = false" size="small">取 消</el-button>
      <el-button type="primary" @click="submitDeleteRole" size="small" v-preventReClick>确 定</el-button></span></el-dialog>
  <!-- 分配-->
  <el-dialog class="delete" title="权限分配" top="33vh" align="center" :visible.sync="allocationPermission" :append-to-body="true" @close="cancle" width="30%">
    <el-tree :data="permissionData" show-checkbox node-key="id" ref="tree" :default-checked-keys="defaultExpandedKeys" :props="defaultProps"></el-tree><span class="dialog-footer" slot="footer">
      <el-button @click="cancle" size="small">取 消</el-button>
      <el-button type="primary" @click="submitSetPermission" size="small" v-preventReClick>确 定</el-button></span>
  </el-dialog>
</div></template>

<script>
import { rolesList, addRole, permissionList, submitCheckedPermission, savePermission, deletePermission ,listMenusByRoleId} from '@/api/getData'

export default {
  name: 'RoleManagement',
  data() {
    return {
      maxPage: 1,
      tableData: [],
      pageSize: 10,
      currentPage: 1,
      total: 0,
      multipleSelection: [],
      value: false,
      tableLoading: false,
      deleteRoles: false,
      allocationPermission: false,
      name: '',
      insertTime: '',
      role: '',
      permissionData: [],
      defaultExpandedKeys: [],
      defaultCheckedKeys: [],
      checkedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      permissionId: '',
      deleteId: '',
      pagekey: '',
    }
  },
  async created() {
    this.initData();
    this.pagekey = await this.$getPageKey();
  },
  methods: {
    // 初始化角色列表
    async initData() {
      this.tableData = []
      const returnData = await rolesList({
        page: {
          current: this.currentPage + '',
          size: this.pageSize + '',
          ascs: this.ascs,
          descs: this.descs
        }
      })
      this.tableData = [];
      this.total = 0;
      if (returnData._result) {
        returnData.data.records.map(item => {
          const obj = {}
          obj.id = item.id
          obj.name = item.name
          obj.insertTime = item.insertTime
          obj.roleChar = item.roleChar
          this.tableData.push(obj)
        })
        this.total = returnData.data.total;
      }
    },
    // 增加角色
    async addRoles() {
      if(this.role===''){
        this.$message.error("请输入角色名字")
        return ;
      }
      const returnData = await addRole({
        name: this.role
      },{
        pagekey: this.pagekey
      });
      if (returnData._result) {
        if (this.role) {
          this.$message({ message: '角色添加成功！', type: 'success' });
          this.initData()
        }
      }
      this.pagekey = await this.$getPageKey();
    },
    // 显示删除提示框
    async showDeleteRole(role) {
      this.deleteId = role.id;
      this.deleteRoles = true
    },
    // 显示角色对应的权限
    async showAllocationPermission(role) {

      /******************* 获取所有的权限********************/

      this.defaultExpandedKeys = []
      this.permissionId = role.id
      this.allocationPermission = true
      const returnData = await permissionList({
        id: this.permissionId
      })

      this.permissionData = []
      if (returnData._result) {
        const baseNode = returnData.data.filter(element => {
          return element.pid === '0'
        })
        this.permissionData.push(...baseNode)
        this.getChildren(this.permissionData, returnData.data)
      }


      /******************* 获取所有的权限********************end/
       *
      /******************* 获取所角色权限********************/
    const returnData1 = await listMenusByRoleId({
        id: this.permissionId
      })

      if (returnData1._result) {
        let res= returnData1.data.map(item => {

          return item.id;
        })

        res.map(v=>{
          this.$refs.tree.setChecked(v,true,false)
        })

      }




    },
    // 提交删除
    async submitDeleteRole() {
      const returnData = await deletePermission({
        id: this.deleteId
      })
      if (returnData._result) {
        this.deleteRoles = false
        this.$message({ message: '角色删除成功！', type: 'success' })
        this.initData()
      }
    },
    // 提交角色权限设置
    async submitSetPermission() {
      let parentArr = this.$refs.tree.getHalfCheckedKeys();
      let childArr = this.$refs.tree.getCheckedKeys();
      parentArr=parentArr.concat(childArr);
      const returnData = await savePermission({
        roleId: this.permissionId,
        ids: parentArr
      },{
        pagekey: this.pagekey
      });
      if (returnData._result) {
        this.allocationPermission = false
        this.$message({ message: '权限设置成功!', type: 'success' })
        this.$refs.tree.setCheckedKeys([]);
      }
      this.pagekey = await this.$getPageKey();
    },
    // 选中的权限
    slesCheck() {

    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.initData()
    },
    // 递归权限列表
    getChildren(nodeList, jsonData) {
      const that = this
      nodeList.forEach(function(element) {
        element.children = jsonData.filter(function(item) {
          return item.pid === element.id
        })
        if (element.children.length > 0) {
          that.getChildren(element.children, jsonData)
        }
      })
    },
    cancle(){
      this.$refs.tree.setCheckedKeys([]);
      this.allocationPermission = false
    }
  }
}
</script>

<style scoped lang="scss">

.el-popper[x-placement^=bottom] {
  margin-right: -39px;
  box-shadow: 0 0 10px #888888;
  margin-left: 6px;

  .operation {
    border: 0;
    outline: none;
    display: block;
    text-align: center;
    margin: 0;
  }
}
.el-popper[x-placement^=top] {
  box-shadow: 0 0 10px #888888;
  margin-left: 6px;
  margin-right: -39px;
  button {
    display: block;
  }
  .operation {
    border: 0;
    outline: none;
    display: block;
    text-align: center;
    margin: 0;
  }
}
</style>
